package com.camartsApp.controller;

import com.camartsApp.service.SearchService;
import com.camartsApp.entity.Search;
import com.camartsApp.Util.Response;
import com.camartsApp.common.ResultVO;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/search")
public class SearchController {

    private final SearchService searchService;

    public SearchController(SearchService searchService) {
        this.searchService = searchService;
    }

    // 统一搜索接口，返回两种搜索结果
    @GetMapping("/search-all/{keyword}")
    public ResultVO searchAll(@PathVariable("keyword") String keyword) {
        Map<String, List<Search>> results = searchService.searchAll(keyword);
        if (results == null) {
            return Response.FailResultByMsg("搜索服务异常");
        }

        // 检查是否有任何类型的搜索结果
        boolean hasUserResults = results.get("userResults") != null && !results.get("userResults").isEmpty();
        boolean hasTitleResults = results.get("titleResults") != null && !results.get("titleResults").isEmpty();

        if (!hasUserResults && !hasTitleResults) {
            return Response.FailResultByMsg("未找到相关结果");
        }

        // 构建返回消息
        StringBuilder message = new StringBuilder("查询成功");
        if (hasUserResults && hasTitleResults) {
            message.append("，找到用户和帖子");
        } else if (hasUserResults) {
            message.append("，仅找到用户");
        } else {
            message.append("，仅找到帖子");
        }

        return Response.OkByDataAndMsg(results, message.toString());
    }

    // 用户搜索接口
    @GetMapping("/search-users/{nickname}")
    public ResultVO getUsersByNickname(@PathVariable("nickname") String nickname) {
        List<Search> users = searchService.getUsersByNickname(nickname);
        if (users == null || users.isEmpty()) {
            return Response.FailResultByMsg("未找到该昵称的用户");
        }
        return Response.OkByDataAndMsg(users, "查询成功");
    }
}
